import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';

// 导入文件选择包
import 'package:file_picker/file_picker.dart';

// 导入数据库类
import '../db/booksManager.dart';

import 'package:ibook/bookdetail/bookDetail.dart';
// 请求文件访问权限
import 'package:permission_handler/permission_handler.dart';

import 'package:path_provider/path_provider.dart';
import 'package:ibook/bookshelf/permission.dart';

// 有状态控件含有数据 关键字 StatefulWidget
class BookSelf extends StatefulWidget {
  const BookSelf({Key? key}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _bookshelfState createState() => _bookshelfState();
}

// 状态控制类
// 有状态控件必须结合一个状态管理类，来进行实现
// ignore: camel_case_types
class _bookshelfState extends State<BookSelf> with AutomaticKeepAliveClientMixin {
  bool fileSelected = false; // 初始化文件选择状态
  String fileInfo = "";
  List<Map<String, dynamic>> books = []; //导入的所有书籍
  String bookname = "";
  int booksize = 0;
  final databaseManager = booksManager();
  // 用来表示是否插入成功的标志
  int successFlag = 0;
  //页面加载动画
  bool isLoading = true;

  @override
  bool get wantKeepAlive => true; // 保持页面状态

//私有文件夹路径

// 初始化
  @override
  void initState() {
    super.initState();
    // 初始化数据库
    _dbinit();
    // _getProviateFilePath();
    print("刷新成功");
    // reloadBooksData();
  }

  // 初始化数据库
  void _dbinit() async {
    // final databaseManager = booksManager();
    await databaseManager.initializeDatabase();
    // await databaseManager.deleteTableBooks();
    // await databaseManager.deleteDataFromBookContent(0);
    books = await databaseManager.getAllBooks();
    print("result:" + books.toString());
    // // 获取数据后，刷新
    setState(() {});
    // return result;
  }

  // 书籍项跳转到详情页面

  void turnToDetailPage(file) async {
    // print("测试：${file['path']}");
    // 跳转到详情页面,携带参数
    Navigator.push(context, MaterialPageRoute(builder: (context) => BookDetail(), settings: RouteSettings(arguments: file)));
  }

  // 删除导入的书籍
  void deletePickedBook(file) async {
    await databaseManager.deleteRowDataFromBooks(file["bookName"]);
    books = await databaseManager.getAllBooks();
    setState(() {});
    // print("${file?["bookName"]}");
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 添加这一行来调用超类的 build 方法
    return SingleChildScrollView(
        child: Padding(
      padding: const EdgeInsets.all(24),
      // isLoading
      //     ? Center(
      //         child: CircularProgressIndicator(),
      //       )
      //     :
      child: Wrap(
        alignment: WrapAlignment.start,
        spacing: 20,
        runSpacing: 15,
        children: [
          // 循环渲染数组 ，导入的书籍
          ...books.map((file) {
            return GestureDetector(
              // 点击事件
              onTap: () {
                //
                turnToDetailPage(file);
              },
              // 长按事件
              onLongPress: () {
                // deletePickedBook(file);
                showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      title: Text("确认删除？"),
                      content: Text("您确定要删除 ${file["bookName"]} 吗？"),
                      actions: <Widget>[
                        TextButton(
                          child: Text("取消"),
                          onPressed: () {
                            Navigator.of(context).pop(); // 关闭对话框
                          },
                        ),
                        TextButton(
                          child: Text("删除"),
                          onPressed: () {
                            // 在这里执行删除操作，例如从数据库中删除书籍
                            deletePickedBook(file);
                            Navigator.of(context).pop(); // 关闭对话框
                          },
                        ),
                      ],
                    );
                  },
                );
              },
              child: Container(
                width: 90,
                height: 180,
                // decoration: BoxDecoration(color: const Color.fromARGB(255, 239, 246, 247), border: Border.all(color: Colors.black, width: 1)),
                decoration: BoxDecoration(
                  color: Color(0xffAFC8B2),
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color: const Color(0xff8FA678), width: 1),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3),
                      offset: Offset(0, 4),
                      blurRadius: 1,
                      spreadRadius: 1,
                    )
                  ],
                ),
                padding: const EdgeInsets.all(12),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min, // 关键属性：使列高度自适应内容
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Center(
                      child: Text(
                        "${file["bookName"]}",
                        style: TextStyle(color: Colors.white, fontSize: 16),
                        textAlign: TextAlign.center,
                      ),
                    )
                  ],
                ),
              ),
            );
          }).toList(),
          // 导入按钮
          Container(
            width: 90,
            height: 180,
            // decoration: BoxDecoration(color: const Color.fromARGB(255, 239, 246, 247), border: Border.all(color: Colors.black, width: 1)),
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(5), border: Border.all(color: const Color(0xff8FA678), width: 1), boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                offset: Offset(0, 4),
                blurRadius: 1,
                spreadRadius: 1,
              )
            ]),
            // padding: const EdgeInsets.all(12),
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Color(0xffAFC8B2),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(5),
                ),
                elevation: 0, // 移除默认阴影
                padding: EdgeInsets.zero, // 移除默认内边距
              ),
              onPressed: (() {
                _openFilePicker();
              }),
              child: Text(
                "+",
                style: TextStyle(fontSize: 32, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    ));
  }

// 文件选择类
  void _openFilePicker() async {
    try {
      // 请求存储权限
      bool hasPermission = await PermissionService.requestStoragePermission();

      if (!hasPermission) {
        // 权限被拒绝，提示用户
        _showPermissionDeniedDialog();
        return;
      }

      // 权限已获取，打开文件选择器
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['txt', 'pdf', 'epub'], // 根据需要调整
      );

      if (result != null) {
        _processSelectedFile(result);
      } else {
        print("用户取消了文件选择");
      }
    } catch (e) {
      print("文件选择错误: $e");
      _showErrorDialog('文件选择失败: $e');
    }
  }

  void _showPermissionDeniedDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("需要存储权限"),
          content: Text("此应用需要存储权限来访问书籍文件"),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text("取消"),
            ),
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop();
                await openAppSettings();
              },
              child: Text("去设置"),
            ),
          ],
        );
      },
    );
  }

  void _showErrorDialog(String message) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
  }

  void _processSelectedFile(FilePickerResult result) {
    setState(() {
      fileSelected = true;
      PlatformFile file = result.files.first;

      // 使用正则表达式来获取书名
      RegExp regex = RegExp(r'《(.*?)》');
      String? bookname;
      Iterable<Match> matches = regex.allMatches(file.name);
      for (Match match in matches) {
        var extractedString = match.group(1);
        bookname = extractedString;
      }
      if (bookname == null) {
        bookname = file.name;
      }

      var book = {"id": 0, "bookName": bookname, "name": file.name, "content": '', "catalogue": '', "bookmark": "", "path": file.path};

      print("选择的文件路径：${file.path}");
      dbOption(book);
    });
  }

// 文件操作
  void copyFile() async {
    Directory appPrivateDir = await getApplicationDocumentsDirectory();
    print("私有路径：${appPrivateDir.path}");
    // File(newPath).copy(filePath);
  }

  // 数据库操作
  dbOption(book) async {
    // 将选择的数据插入到数据库中
    successFlag = await databaseManager.insertBook(book);
    if (successFlag != 1) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('导入失败'),
            content: Text('数据已存在'),
            actions: <Widget>[
              TextButton(
                child: Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop(); // 关闭对话框
                },
              ),
            ],
          );
        },
      );
    }
    // 从数据库中获取所有的数据
    books = await databaseManager.getAllBooks();
    setState(() {});
    // return books;
  }
}
